package top.zosoft.handler.adapter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import top.zosoft.annotation.Process;
import top.zosoft.handler.MqttHandler;
import top.zosoft.utils.ServiceException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author neal
 * @date 2023/12/20  10:11
 */
@Component
@Slf4j
public class MqttMessageDelegate {
    private final Map<MqttMessageType, MqttHandler> processor = new HashMap<>();

    public MqttMessageDelegate(@Autowired List<MqttHandler> handlers) {
        if (CollectionUtils.isEmpty(handlers)) {
            throw new ServiceException("报文处理类为空");
        }
        handlers.forEach(handler -> {
            Process annotation = handler.getClass().getAnnotation(Process.class);
            Optional.ofNullable(annotation).map(process -> process.type())
                    .ifPresent(messageType -> processor.put(messageType, handler));
        });
    }

    public void process(ChannelHandlerContext ctx, MqttMessage msg) {
        MqttMessageType messageType = msg.fixedHeader().messageType();

//        if (MqttMessageType.CONNECT != messageType &&
//                AttributeUtils.getSession(ctx.channel()) == null){
//            log.error("=>客户端未连接");
//            throw new ServiceException("客户端未连接");
//        }
        Optional.of(processor.get(messageType))
                .ifPresent(mqttHandler -> mqttHandler.handler(ctx, msg));

    }

}
